package com.bookcycle.panda.webfront.controller;

import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.security.token.SSOToken;
import com.bookcycle.panda.webfront.constant.URLConstant;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
public class HouseController extends BaseController{


    /**
     * 连接看房
     * @param houseId
     * @param model
     * @return
     */
    @RequestMapping(value = "/applyRoom",method = RequestMethod.GET)
    public String applyRoom(@RequestParam("houseId") String houseId, Model model){
        SSOToken ssoToken=SSOHelper.getSSOToken(request);
        if(ssoToken==null){
            return "redirect:signIn";
        }else {
            String url="http://58.87.74.194:8029/applyroom?requestBody=";
            String userId=ssoToken.getId();
            String json="{\"userId\":"+userId+",\"roomId\":"+houseId+"}";
            try {
                String u= URLEncoder.encode(json,"utf-8");
                return "redirect:"+url+u;
            }catch (UnsupportedEncodingException e){
                e.toString();
            }
        }
        return "home";
    }

    /**
     * 显示房屋详情
     * @param houseId
     * @param model
     * @return
     */
    @RequestMapping(value = "/showHouse",method = RequestMethod.GET)
    public String showHouse(@RequestParam("houseId") String houseId, Model model){
        RestTemplate restTemplate=new RestTemplate();
        Map<String,String> map=new HashMap<String,String>();
        map.put("id",houseId);
        try{
            ResponseEntity<Object> responseEntity=restTemplate.getForEntity(URLConstant.URL_GET_HOUSE,Object.class,map);
            JSONObject jsonObject=JSONObject.fromObject(responseEntity.getBody());
            model.addAttribute("area",jsonObject.get("area"));
            model.addAttribute("images",jsonObject.get("images"));
            model.addAttribute("orientation",jsonObject.get("orientation"));
            model.addAttribute("houseType",jsonObject.get("houseType"));
            model.addAttribute("price",jsonObject.get("price"));

        }catch (HttpClientErrorException e){
            return e.toString();
        }

        model.addAttribute("houseId",houseId);
        return "house";
    }
}
